package io.adrainty.bolee.framework.redis.configuration;

import cn.hutool.core.text.StrPool;
import io.adrainty.bolee.framework.redis.properties.DataSecurityCacheProperties;
import io.adrainty.bolee.framework.redis.resolver.FrameworkRedisCacheManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cache.CacheManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.CacheKeyPrefix;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import java.time.Duration;

/**
 * <p>FrameworkRedisCacheConfig</p>
 *
 * @author AdRainty
 * @version V1.0.0
 * @description RedisCacheConfig
 * @since 2025/8/1 15:27:33
 */

@Configuration
@EnableConfigurationProperties({
        DataSecurityCacheProperties.class
})
public class FrameworkRedisCacheConfig {

    /**
     * 缓存key前缀
     * @return CacheKeyPrefix
     */
    @Bean
    public CacheKeyPrefix cacheKeyPrefix() {
        return cacheName -> cacheName + StrPool.COLON;
    }

    @Bean
    public CacheManager cacheManager(@Autowired RedisConnectionFactory redisConnectionFactory, @Autowired DataSecurityCacheProperties properties) {
        RedisSerializer<String> keySerializer = new StringRedisSerializer();
        GenericJackson2JsonRedisSerializer valuesSerializer = new GenericJackson2JsonRedisSerializer();
        RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig()
                .computePrefixWith(cacheKeyPrefix())
                .entryTtl(Duration.ofHours(1))
                .serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(keySerializer))
                .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(valuesSerializer));
        return new FrameworkRedisCacheManager(redisConnectionFactory, config, properties);
    }

}
